package com.xinqi.modules.chat.chat.friend.service.impl;

import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.core.utils.MessageUtils;
import com.xinqi.modules.chat.chat.friend.convert.ChatFriendApplyMessageConvert;
import com.xinqi.modules.chat.chat.friend.domain.ChatFriendApplyMessageEntity;
import com.xinqi.modules.chat.chat.friend.dto.req.ChatFriendApplyMessageCreateDTO;
import com.xinqi.modules.chat.chat.friend.dto.rsp.ChatFriendApplyMessageResultDTO;
import com.xinqi.modules.chat.chat.friend.manager.ChatFriendApplyMessageManager;
import com.xinqi.modules.chat.chat.friend.service.ChatFriendApplyMessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 申请加好友消息内容服务层实现
 *
 * @author: system
 * @date: 2023/01/12
 */
@Service("chatFriendApplyMessageService")
@RequiredArgsConstructor
public class ChatFriendApplyMessageServiceImpl implements ChatFriendApplyMessageService {
    private final ChatFriendApplyMessageConvert chatFriendApplyMessageConvert;
    private final ChatFriendApplyMessageManager chatFriendApplyMessageManager;

    /**
     * 新增 申请加好友消息内容数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(ChatFriendApplyMessageCreateDTO dto) {
        CommonErrors.BAD_REQUEST.check(Objects.nonNull(dto.getApplyId()), MessageUtils.message("chat.friend.apply.id.not.blank"));
        //被回复了才能再次发起一条消息
        ChatFriendApplyMessageEntity chatFriendApplyMessageEntity = chatFriendApplyMessageManager.selectNewFriendApplyMessageByApplyId(dto.getApplyId());
        if (Objects.nonNull(chatFriendApplyMessageEntity)) {
            CommonErrors.BAD_REQUEST.check(!Objects.equals(dto.getOperationUserId(), chatFriendApplyMessageEntity.getUserId()), MessageUtils.message("chat.friend.apply.message.not.blank"));
        }
        ChatFriendApplyMessageEntity entity = chatFriendApplyMessageConvert.create(dto);
        entity.setUserId(dto.getOperationUserId());
        chatFriendApplyMessageManager.save(entity);
        return entity.getId();
    }

    /**
     * 根据申请ID获取申请消息列表
     *
     * @param applyId
     * @return
     */
    @Override
    public List<ChatFriendApplyMessageResultDTO> findByApplyId(Long applyId) {
        return chatFriendApplyMessageManager.findByApplyId(applyId);
    }
}
